<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <el-button @click="handleDlg(0)">添加</el-button>
    </div>
    <el-table :data="resourceCategoryData" border style="width: 100%">
      <el-table-column type="index" label="编号" width="180" align="center">
      </el-table-column>
      <el-table-column prop="name" label="类别名称" align="center">
      </el-table-column>
      <el-table-column
        prop="createdTime"
        label="创建时间"
        align="center"
        :formatter="timeFormater"
      >
      </el-table-column>
      <el-table-column prop="sort" label="排序" align="center">
      </el-table-column>
      <el-table-column prop="address" label="操作" align="center">
        <template v-slot="scoped">
          <el-button size="mini" @click="handleDlg(scoped.row.id)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            size="mini"
            @click="handleDeleteCateory(scoped.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <resource-category-create-or-update
      ref="categoryDlg"
      @changeCategory="loadAllResourceCategory"
    ></resource-category-create-or-update>
  </el-card>
</template>
<script>
import {
  getAllResourceCategory,
  deleteCategory
} from '@/api/resource-category'
import ResourceCategoryCreateOrUpdate from './create-or-edit.vue'
import dayjs from 'dayjs'

export default {
  name: 'ResourceCategoryIndex',
  components: { ResourceCategoryCreateOrUpdate },
  created () {
    this.loadAllResourceCategory()
  },
  data () {
    return {
      resourceCategoryData: []
    }
  },
  methods: {
    loadAllResourceCategory () {
      getAllResourceCategory().then((res) => {
        if (res.data.code === '000000') {
          this.resourceCategoryData = res.data.data
        } else {
          this.$message.error('获取资源分类失败')
        }
      })
    },
    timeFormater (row, column, value, index) {
      return dayjs(value).format('YYYY-MM-DD')
    },
    handleDlg (categoryId = 0) {
      this.$refs.categoryDlg.showAndInit(categoryId)
    },
    // 删除
    handleDeleteCateory (id) {
      this.$confirm('确认要删除资源类别吗？', '删除提示')
        .then(() => {
          // 如果点确定
          deleteCategory(id).then((res) => {
            if (res.data.data) {
              this.$message.success('删除资源类别成功')
              this.loadAllResourceCategory()
            }
          })
        })
        .catch(() => {
          // 如果点取消
          this.$message.info('取消了删除资源类别的操作')
        })
    }
  }
}
</script>
